new Vue({
    el: '#app',
    data: {
        searchQuery: '',
        notificationCount: 3,
        user: {
            name: '管理员',
            avatar: 'https://randomuser.me/api/portraits/men/41.jpg'
        },
        // 统计数据
        dailySales: 86540,
        monthlySales: 2456800,
        totalSales: 18765400,
        userCount: 24568,
        // 变化率
        dailyChange: 12.5,
        monthlyChange: 8.3,
        totalChange: 23.7,
        userChange: 5.2,
        // 图表数据
        chartRange: 'month',
        loadingSales: false,
        loadingUsers: false,
        salesChart: null,
        usersChart: null,
        //判断是否有数据对比
        hasDayData: true,
        hasMonthData: true,
        hasYearData: true
    },
    mounted() {
        this.initCharts();
        // 模拟初始数据加载
        this.fetchData();
        this.loadingSales = true;
        this.loadingUsers = true;
        setTimeout(() => {
            this.loadingSales = false;
            this.loadingUsers = false;
        }, 1000);
    },
    methods: {
        initCharts() {
            // 初始化销售图表
            const salesCtx = document.getElementById('salesChart').getContext('2d');
            this.salesChart = new Chart(salesCtx, {
                type: 'line',
                data: {
                    labels: ['1月', '2月', '3月', '4月', '5月', '6月', '7月'],
                    datasets: [{
                        label: '销售额 (元)',
                        data: [120, 190, 150, 220, 180, 200, 250],
                        borderColor: '#3498db',
                        backgroundColor: 'rgba(52, 152, 219, 0.1)',
                        borderWidth: 3,
                        pointBackgroundColor: '#fff',
                        pointBorderWidth: 2,
                        pointRadius: 4,
                        tension: 0.3,
                        fill: true
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: false
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            grid: {
                                color: 'rgba(255, 255, 255, 0.1)'
                            },
                            ticks: {
                                color: '#b0b3b8'
                            }
                        },
                        x: {
                            grid: {
                                display: false
                            },
                            ticks: {
                                color: '#b0b3b8'
                            }
                        }
                    }
                }
            });
            //获取每日销售额
            $.ajax({
                url: 'http://localhost:8080/salesStatistics/getMonthSales',
                method: 'GET',
                headers: { token: userId = 1 },
                success: (response) => {
                    if (response.code !== 200 || !response.data) {
                        console.error("无效响应或缺少数据");
                        this.loadingSales = false;
                        return;
                    }

                    const labels = this.getPastSixMonthsLabels(); // 动态生成中文月份标签
                    const salesData = this.mapDataToChart(response.data, labels); // 匹配数据

                    // 更新图表
                    this.salesChart.data.labels = labels;
                    this.salesChart.data.datasets[0].data = salesData;
                    this.salesChart.update();

                    this.loadingSales = false;
                },
                error: () => {
                    alert('加载销售数据失败');
                    this.loadingSales = false;
                }
            })

            // 初始化用户图表
            const usersCtx = document.getElementById('usersChart').getContext('2d');
            this.usersChart = new Chart(usersCtx, {
                type: 'doughnut',
                data: {
                    labels: ['新用户', '活跃用户', '沉睡用户'],
                    datasets: [{
                        data: [35, 50, 15],
                        backgroundColor: [
                            '#3498db',
                            '#2ecc71',
                            '#f39c12'
                        ],
                        borderWidth: 0,
                        hoverOffset: 10
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom',
                            labels: {
                                color: '#b0b3b8',
                                padding: 20,
                                font: {
                                    size: 12
                                }
                            }
                        }
                    },
                    cutout: '70%'
                }
            });
            //获取用户构成数据
            $.ajax({
                url: 'http://localhost:8080/salesStatistics/countUserTypes',
                method: 'GET',
                headers: { token: userId = 1 },
                success: (data) => {
                    if (data.code === 200 && data.data) {
                        this.userCount = data.data.totalUsers; // 假设 totalUsers 是总用户数
                        this.updateUserChart(data.data); // 更新饼图数据
                    } else {
                        console.error("用户数据加载失败或数据缺失");
                    }

                    this.loadingSales = false;
                    this.loadingUsers = false;
                },
                error: () => {
                    alert('刷新用户数据失败');
                    this.loadingSales = false;
                    this.loadingUsers = false;
                }
            })
        },
        changeChartRange(range) {
            this.chartRange = range;
            this.loadingSales = true;

            // 模拟AJAX请求
            $.ajax({
                url: '/api/sales-data',
                method: 'GET',
                data: { range: range },
                success: (data) => {
                    // 在实际应用中，这里会更新图表数据
                    setTimeout(() => {
                        this.loadingSales = false;
                        // 更新图表数据（模拟）
                        this.salesChart.data.datasets[0].data = data;
                        this.salesChart.update();
                    }, 800);
                },
                error: () => {
                    this.loadingSales = false;
                    alert('加载销售数据失败');
                }
            });
        },
        fetchData() {
            // 模拟AJAX请求刷新所有数据
            this.loadingSales = true;
            this.loadingUsers = true;
            // 获取日销售额 
            $.ajax({
                url: 'http://localhost:8080/salesStatistics/calculateTodaySales',
                method: 'GET',
                headers: {
                    token: userId = 1
                },
                success: (data) => {
                    console.log(data);
                    // 更新数据
                    this.dailySales = data.data.todaySales;
                    this.dailyChange = this.calculateDailyChange(this.dailySales, data.data.yesterdaySales);
                    if (!this.dailyChange) {
                        this.hasDayData = false
                    }
                },
                error: () => {
                    this.loadingSales = false;
                    this.loadingUsers = false;
                    alert('刷新数据失败');
                }
            });
            //获取月销售额
            $.ajax({
                url: 'http://localhost:8080/salesStatistics/calculateMonthSales',
                method: 'GET',
                headers: { token: userId = 1 },
                success: (data) => {
                    this.monthlySales = data.data.thisMonthSales;
                    this.monthlyChange = this.calculateDailyChange(this.monthlySales, data.data.preMonthSales);
                    if (!this.monthlyChange) {
                        this.hasMonthData = false
                    }
                },
                error: () => {
                    this.loadingSales = false;
                    this.loadingUsers = false;
                    alert('刷新数据失败');
                }

            })
            //获取年销售额
            $.ajax({
                url: 'http://localhost:8080/salesStatistics/calculateYearsSales',
                method: 'GET',
                headers: { token: userId = 1 },
                success: (data) => {
                    this.totalSales = data.data.thisYearSales;
                    this.totalChange = this.calculateDailyChange(this.yearlySales, data.data.preYearSales);
                    if (!this.yearlyChange) {
                        this.hasYearData = false
                    }
                },
                erro() {
                    this.loadingSales = false;
                    this.loadingUsers = false;
                    alert('刷新数据失败');
                }

            })
            // 获取用户数据 
            $.ajax({
                url: 'http://localhost:8080/salesStatistics/getUserCount',
                method: 'GET',
                headers: { token: userId = 1 },
                success: (data) => {
                    this.userCount = data.data;
                },
                error: () => {
                    this.loadingSales = false;
                    this.loadingUsers = false;
                    alert('刷新数据失败');
                }
            })
        },
        calculateDailyChange(todaySales, yesterdaySales) {
            // 类型检查
            const today = Number(todaySales);
            const yesterday = Number(yesterdaySales);

            if (isNaN(today) || isNaN(yesterday)) {
                console.warn("输入值不是有效的数字");
                return false;
            }

            if (yesterday === 0) {
                console.warn("昨日销售额为零，无法计算变化率");
                return false; // 或者返回 null，根据业务需求决定
            }

            const change = (today - yesterday) / yesterday * 100;

            // 固定两位小数，提升展示精度
            return parseFloat(change.toFixed(4)); // 保留四位用于计算，展示可保留两位
        },
        //销售额处理方法
        getPastSixMonthsLabels() {
            const monthNames = ['JANUARY', 'FEBRUARY', 'MARCH', 'APRIL', 'MAY', 'JUNE',
                'JULY', 'AUGUST', 'SEPTEMBER', 'OCTOBER', 'NOVEMBER', 'DECEMBER'];
            const chineseMap = {
                JANUARY: '1月',
                FEBRUARY: '2月',
                MARCH: '3月',
                APRIL: '4月',
                MAY: '5月',
                JUNE: '6月',
                JULY: '7月',
                AUGUST: '8月',
                SEPTEMBER: '9月',
                OCTOBER: '10月',
                NOVEMBER: '11月',
                DECEMBER: '12月'
            };

            const now = new Date();
            const currentMonthIndex = now.getMonth(); // 从0开始（0=一月）
            const labels = [];

            for (let i = 5; i >= 0; i--) {
                const idx = (currentMonthIndex - i + 12) % 12;
                labels.push(chineseMap[monthNames[idx]]);
            }

            return labels;
        },
        mapDataToChart(responseData, labels) {
            const keyMap = {
                '1月': 'JANUARY',
                '2月': 'FEBRUARY',
                '3月': 'MARCH',
                '4月': 'APRIL',
                '5月': 'MAY',
                '6月': 'JUNE',
                '7月': 'JULY',
                '8月': 'AUGUST',
                '9月': 'SEPTEMBER',
                '10月': 'OCTOBER',
                '11月': 'NOVEMBER',
                '12月': 'DECEMBER'
            };

            return labels.map(label => {
                const key = keyMap[label];
                return responseData[key] !== undefined ? responseData[key] : 0;
            });
        },
        //更新用户构成图数据
        updateUserChart(data) {
            const chartData = [
                data.newUsers || 0,
                data.activeUsers || 0,
                data.dormantUsers || 0,
                data.neverPurchased || 0
            ];

            this.usersChart.data.labels = ['新用户', '活跃用户', '沉睡用户', '未购买用户'];
            this.usersChart.data.datasets[0].data = chartData;
            this.usersChart.data.datasets[0].backgroundColor = ['#3498db', '#2ecc71', '#f39c12', '#e74c3c'];
            this.usersChart.update();
        }


    }
});